package org.yinxue.example.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.yinxue.example.netty.client.handler.HeartBeatClientHandler;
import org.yinxue.example.netty.core.codec.HeartBeatDecoder;
import org.yinxue.example.netty.core.codec.HeartBeatEncoder;
import org.yinxue.example.netty.core.model.HeartBeatRequest;

/**
 * NettyClient {@link org.yinxue.example.netty.client}
 *
 * @author zengjian
 * @date 2019/1/1
 * @since 1.0.0
 */
public class NettyClient {

    private String host;
    private int port;


    private Channel channel;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HeartBeatDecoder());
                        ch.pipeline().addLast(new HeartBeatEncoder());
                        ch.pipeline().addLast(new HeartBeatClientHandler());
                    }
                });

        ChannelFuture future = bootstrap.connect(host, port).syncUninterruptibly();
        channel = future.channel();
        channel.closeFuture().syncUninterruptibly();
    }

    public void pushMessage(HeartBeatRequest request){
        channel.writeAndFlush(request);
    }
}